﻿using System;
using System.Windows.Controls;
using System.Windows.Navigation;
using Songhay.Mvvm.Models;
using Songhay.Mvvm.ViewModels;
using GalaSoft.MvvmLight.Messaging;

namespace Songhay.Mvvm.Extensions
{
    /// <summary>
    /// Extensions for <see cref="System.Windows.Controls.Page"/>.
    /// </summary>
    public static class PageExtensions
    {
        /// <summary>
        /// Handles the <see cref="Page.OnNavigatedFrom"/> method in the View Model.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="e">The <see cref="NavigationEventArgs"/> instance containing the event data.</param>
        public static void HandleOnNavigatedFrom(this Page page, NavigationEventArgs e)
        {
            var vm = page.DataContext as IPageNavigationViewModel;
            if (vm == null) return;
            vm.HandleOnNavigatedFrom(e);
        }

        /// <summary>
        /// Handles the <see cref="Page.OnNavigatedTo"/> method in the View Model.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="e">The <see cref="NavigationEventArgs"/> instance containing the event data.</param>
        public static void HandleOnNavigatedTo(this Page page, NavigationEventArgs e)
        {
            var vm = page.DataContext as IPageNavigationViewModel;
            if (vm == null) return;
            vm.HandleOnNavigatedTo(e);
        }

        /// <summary>
        /// Sends the light message for view navigated from.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="e">The <see cref="NavigationEventArgs"/> instance containing the event data.</param>
        /// <param name="messageUniqueId">The message unique id.</param>
        public static void SendLightMessageForViewNavigatedFrom(this Page page, NavigationEventArgs e, string messageUniqueId)
        {
            var message = new LightMessage<NavigationEventArgs>(e)
            {
                Source = LightMessageSource.ViewNavigatedFrom,
                UniqueId = messageUniqueId
            };
            Messenger.Default.Send(message);
        }

        /// <summary>
        /// Sends the light message for view navigated to.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="e">The <see cref="NavigationEventArgs"/> instance containing the event data.</param>
        /// <param name="messageUniqueId">The message unique id.</param>
        public static void SendLightMessageForViewNavigatedTo(this Page page, NavigationEventArgs e, string messageUniqueId)
        {
            var message = new LightMessage<NavigationEventArgs>(e)
            {
                Source = LightMessageSource.ViewNavigatedTo,
                UniqueId = messageUniqueId
            };
            Messenger.Default.Send(message);
        }
    }
}
